<template>
  <div class="third-party-sync">
    <el-form ref="formRef" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="任务描述" prop="jobDesc">
        <el-input v-model="form.jobDesc" style="width: 500px;" />
      </el-form-item>
      <el-form-item label="接口路径" prop="interfaceUrl">
        <el-input v-model="form.interfaceUrl" style="width: 500px;" />
      </el-form-item>
      <el-form-item label="body入参" prop="interfaceBody">
        <el-input v-model="form.interfaceBody" style="width: 500px;" />
      </el-form-item>
      <el-form-item label="系统标准接口" prop="isStandardInterface">
        <el-select v-model="form.isStandardInterface" placeholder="请选择" style="width: 500px;">
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据库源" prop="datasourceId">
        <el-select
          v-model="form.datasourceId"
          placeholder="请选择数据库源"
          style="width: 500px;"
          @change="fetchTableSchema"
        >
          <el-option
            v-for="item in datasources"
            :key="item.id"
            :label="item.datasourceName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Schema" prop="schema">
        <el-select v-model="form.schema" placeholder="请选择Schema" style="width: 500px;" @change="fetchTables">
          <el-option
            v-for="item in schemas"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据库表名" prop="tableName">
        <div style="display: flex;">
          <el-select v-model="form.tableName" placeholder="请选择数据库表名" style="width: 240px;" @change="handleTableChange">
            <el-option v-for="item in tables" :key="item" :label="item" :value="item" />
          </el-select>
          <el-input v-model="form.customTableName" placeholder="或输入自定义表名" style="width: 240px; margin-left: 20px;" @input="handleCustomTableInput" />
        </div>
      </el-form-item>
      <el-form-item label="三方密钥" prop="thirdPartyType">
        <el-select
          v-model="form.configId"
          placeholder="请选择三方密钥"
          style="width: 500px;"
          @change="handleThirdPartyTypeChange"
        >
          <el-option
            v-for="item in thirdPartyTypes"
            :key="item.id"
            :label="item.configName"
            :value="item.id"
            :data-third-type="item.thirdType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="同步表唯一键" prop="uniqueKey">
        <el-input v-model="form.uniqueKey" style="width: 500px;" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as dsQueryApi from '@/api/datax-jdbcDatasource'
import * as apiManageApi from '@/api/third-api-manage'
import * as metaDataApi from '@/api/metadata-query'

export default {
  data() {
    return {
      form: {
        jobDesc: '',
        interfaceUrl: '',
        interfaceBody: '',
        datasourceId: '',
        schema: '',
        tableName: '',
        thirdPartyType: '',
        uniqueKey: '',
        configId: '',
        isStandardInterface: true,
        customTableName: ''
      },
      rules: {
        interfaceUrl: [{ required: true, message: '请输入接口名称', trigger: 'blur' }],
        jobDesc: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
        interfaceBody: [{ required: false, message: '请输入body入参', trigger: 'blur' }],
        isStandardInterface: [{ required: true, message: '请勾选系统接口', trigger: 'blur' }],
        datasourceId: [{ required: true, message: '请选择数据库源', trigger: 'change' }],
        schema: [{ required: true, message: '请选择Schema', trigger: 'change' }],
        tableName: [
          { required: false, message: '请选择或输入数据库表名', trigger: 'change' },
          { validator: this.validateTableName, trigger: 'change' }
        ],
        thirdPartyType: [{ required: true, message: '请选择三方类型', trigger: 'change' }],
        uniqueKey: [{ required: true, message: '请输入同步表唯一键', trigger: 'blur' }]
      },
      datasources: [],
      thirdPartyTypes: [],
      schemas: [],
      tables: [],
      jobTemplates: [],
      datasourcePage: {
        current: 1,
        size: 200
      },
      thirdPartyTypePage: {
        page: 1,
        pageSize: 200
      },
      jobTemplateDialogVisible: false
    }
  },
  created() {
    this.fetchDatasources()
    this.fetchThirdPartyTypes()
  },
  computed: {
    fullTableName() {
      if (this.form.customTableName) {
        return `${this.form.schema}.${this.form.customTableName}`
      }
      return this.form.tableName
    }
  },

  methods: {
    handleSubmit() {
      return new Promise((resolve) => {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            const finalForm = {
              ...this.form,
              tableName: this.fullTableName
            }
            console.log('最终提交数据:', finalForm)
            resolve(true)
          } else {
            this.$message.error('请检查表单信息')
            resolve(false)
          }
        })
      })
    },

    handleReset() {
      this.$refs.formRef.resetFields()
      this.form.customTableName = ''
    },

    fetchDatasources() {
      dsQueryApi.list(this.datasourcePage).then(response => {
        const { records } = response
        this.datasources = this.datasources.concat(records)
      }).catch(error => {
        this.$message.error('获取数据库源失败，请稍后再试' + error)
      })
    },

    fetchThirdPartyTypes() {
      apiManageApi.searchThirdConfig(this.thirdPartyTypePage).then(response => {
        const { records } = response
        this.thirdPartyTypes = this.thirdPartyTypes.concat(records)
      }).catch(error => {
        this.$message.error('获取三方类型失败，请稍后再试' + error)
      })
    },

    fetchTableSchema() {
      this.form.schema = []
      metaDataApi.getTableSchema({ datasourceId: this.form.datasourceId }).then(response => {
        this.schemas = response
      }).catch(error => {
        this.$message.error('获取Schema失败，请稍后再试' + error)
      })
    },

    fetchTables() {
      metaDataApi.getTables({
        datasourceId: this.form.datasourceId,
        tableSchema: this.form.schema
      }).then(response => {
        this.tables = response
        this.form.tableName = ''
        this.form.customTableName = ''
      }).catch(error => {
        this.$message.error('获取数据库表名失败，请稍后再试' + error)
      })
    },

    handleThirdPartyTypeChange(value) {
      const selectedType = this.thirdPartyTypes.find(item => item.id === value)
      if (selectedType) {
        this.form.thirdPartyType = selectedType.thirdType
      }
    },

    handleTableChange() {
      if (this.form.tableName) {
        this.form.customTableName = ''
      }
    },
    handleCustomTableInput() {
      if (this.form.customTableName) {
        this.form.tableName = ''
      }
    },
    validateTableName(rule, value, callback) {
      if (!this.form.tableName && !this.form.customTableName) {
        callback(new Error('请选择或输入数据库表名'))
      } else {
        callback()
      }
    },
    getFinalFormData() {
      return {
        ...this.form,
        tableName: this.fullTableName
      }
    }
  }
}
</script>

<style scoped>
.third-party-sync {
  padding: 20px;
}
</style>
